package com.example.lenovo.wechat;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

import model.LogonPacket;

public class ChatActivity extends AppCompatActivity {
    private List<Msg> msgList = new ArrayList<>();

    private EditText inputText;

    private Button send;

    private RecyclerView msgRecyclerView;

    private MsgAdapter adapter;

    private boolean mRun;

    private String mMessageWaitingForSend = null;

    public Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0x1001) {
                adapter.notifyItemInserted(msgList.size() - 1);
                msgRecyclerView.scrollToPosition(msgList.size() - 1);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        initMsg();

        inputText = findViewById(R.id.input_text);
        send = findViewById(R.id.send);
        msgRecyclerView = findViewById(R.id.msg_recycler_view);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        msgRecyclerView.setLayoutManager(layoutManager);
        adapter = new MsgAdapter(msgList);
        msgRecyclerView.setAdapter(adapter);

        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String s = inputText.getText().toString();
                if (!"".equals(s)) {
                    mMessageWaitingForSend = s;
                    Msg msg = new Msg(s, Msg.Type.SENT);
                    msgList.add(msg);
                    adapter.notifyItemInserted(msgList.size() - 1);
                    msgRecyclerView.scrollToPosition(msgList.size() - 1);
                    inputText.setText("");
                }
            }
        });


        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d("ChatActivity", "Thread start run");
                mRun = true;
                try {
                    Log.d("ChatActivity", "start connect to 10.0.2.2");
                    Socket connection = new Socket("192.168.49.51", 2018);
                    Log.d("ChatActivity", "after connect to 10.0.2.2");
                    OutputStream out = connection.getOutputStream();
                    InputStream in = connection.getInputStream();
                    byte[] readBuffer = new byte[1024];
                    while(mRun) {
                        Log.d("ChatActivity", "Thread run" + mMessageWaitingForSend);
                        if (mMessageWaitingForSend != null) {
                            LogonPacket packet = new LogonPacket();
                            packet.userName = mMessageWaitingForSend;
                            packet.password = "123456";

                            out.write(packet.serialize());
                            out.flush();
                            int length = in.read(readBuffer);
                            String reply = new String(readBuffer, 0, length);
                            Log.d("ChatActivity++++++++++", reply);
                            msgList.add(new Msg(reply, Msg.Type.RECEIVED));
                            mMessageWaitingForSend = null;
                            mHandler.sendEmptyMessage(0x1001);
                        }

                        Thread.sleep(1000);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Log.d("ChatActivity", "Thread stop run");
            }
        }).start();
    }

    public void initMsg() {
        Msg msg1 = new Msg("Hello guy", Msg.Type.RECEIVED);
        msgList.add(msg1);
        Msg msg2 = new Msg("hello. who is that?", Msg.Type.SENT);
        msgList.add(msg2);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mRun = false;
    }
}